package org.example.new_hbps_backend_reconstruction.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.entity.PatientAvatarEntity;
import org.example.new_hbps_backend_reconstruction.mapper.PatientAvatarMapper;
import org.example.new_hbps_backend_reconstruction.service.OssService;
import org.example.new_hbps_backend_reconstruction.service.PatientAvatarService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author Gao Zihan
 * @date 2025年10月16日
 * @description 患者头像服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PatientAvatarServiceImpl extends ServiceImpl<PatientAvatarMapper, PatientAvatarEntity> implements PatientAvatarService {

    private final PatientAvatarMapper patientAvatarMapper;
    private final OssService ossService;

    // 支持的头像文件格式
    private static final List<String> SUPPORTED_FORMATS = Arrays.asList("jpg", "jpeg", "png", "gif", "webp");

    // 最大文件大小 (5MB)
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PatientAvatarEntity uploadAvatar(Long patientUid, MultipartFile file) {
        // 参数验证
        if (patientUid == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("头像文件不能为空");
        }

        // 文件格式验证
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        String fileExtension = getFileExtension(originalFilename).toLowerCase();
        if (!SUPPORTED_FORMATS.contains(fileExtension)) {
            throw new IllegalArgumentException("不支持的文件格式，仅支持: " + String.join(", ", SUPPORTED_FORMATS));
        }

        // 文件大小验证
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小不能超过5MB");
        }

        try {
            // 生成唯一文件名
            String fileName = generateUniqueFileName(patientUid, fileExtension);
            String objectName = "patient-avatars/" + fileName;

            // 上传到OSS
            String avatarUrl = ossService.uploadFileAndGetUrl(file, objectName);
            if (StrUtil.isBlank(avatarUrl)) {
                throw new RuntimeException("头像上传失败");
            }

            // 将之前的头像设为非当前状态
            patientAvatarMapper.updateAllAvatarToNonCurrent(patientUid);

            // 创建头像记录
            PatientAvatarEntity avatarEntity = new PatientAvatarEntity();
            avatarEntity.setPatientUid(patientUid);
            avatarEntity.setAvatarUrl(avatarUrl);
            avatarEntity.setAvatarType("image");
            avatarEntity.setFileSize((int) file.getSize());
            avatarEntity.setFileFormat(fileExtension);
            avatarEntity.setIsCurrent(true);
            avatarEntity.setUploadTime(LocalDateTime.now());
            avatarEntity.setCreatedBy("system");
            avatarEntity.setUpdatedTime(LocalDateTime.now());

            // 保存到数据库
            save(avatarEntity);

            log.info("患者头像上传成功，患者ID: {}, 头像URL: {}", patientUid, avatarUrl);
            return avatarEntity;

        } catch (Exception e) {
            log.error("患者头像上传失败，患者ID: {}", patientUid, e);
            throw new RuntimeException("头像上传失败: " + e.getMessage());
        }
    }

    @Override
    public PatientAvatarEntity getCurrentAvatar(Long patientUid) {
        if (patientUid == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }

        PatientAvatarEntity currentAvatar = patientAvatarMapper.selectCurrentAvatarByPatientUid(patientUid);

        if (currentAvatar == null) {
            try {
                // 设置默认头像并获取结果
                boolean success = setDefaultAvatar(patientUid);
                if (success) {
                    // 重新查询最新的默认头像
                    return patientAvatarMapper.selectCurrentAvatarByPatientUid(patientUid);
                }
            } catch (Exception e) {
                log.error("设置默认头像失败", e);
            }
        }

        return currentAvatar;
    }


    @Override
    public List<PatientAvatarEntity> getAvatarHistory(Long patientUid) {
        if (patientUid == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }
        return patientAvatarMapper.selectAvatarHistoryByPatientUid(patientUid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAvatar(Long avatarId) {
        if (avatarId == null) {
            throw new IllegalArgumentException("头像ID不能为空");
        }

        try {
            PatientAvatarEntity avatar = getById(avatarId);
            if (avatar == null) {
                throw new IllegalArgumentException("头像不存在");
            }

            // 如果是当前头像，不能删除
            if (avatar.getIsCurrent()) {
                throw new IllegalArgumentException("不能删除当前使用的头像");
            }

            // 从OSS删除文件
            String objectName = extractObjectNameFromUrl(avatar.getAvatarUrl());
            if (StrUtil.isNotBlank(objectName)) {
                try {
                    ossService.deleteFile(objectName);
                } catch (Exception e) {
                    log.warn("删除OSS文件失败: {}", objectName, e);
                }
            }

            // 从数据库删除记录
            return removeById(avatarId);

        } catch (Exception e) {
            log.error("删除头像失败，头像ID: {}", avatarId, e);
            throw new RuntimeException("删除头像失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultAvatar(Long patientUid) {
        if (patientUid == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }

        try {
            // 将之前的头像设为非当前状态
            patientAvatarMapper.updateAllAvatarToNonCurrent(patientUid);

            // 创建默认头像记录
            PatientAvatarEntity defaultAvatar = new PatientAvatarEntity();
            defaultAvatar.setPatientUid(patientUid);
            defaultAvatar.setAvatarUrl("https://new-hbps-backend.oss-cn-beijing.aliyuncs.com/patient-avatars/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.jpg"); // 默认头像路径
            defaultAvatar.setAvatarType("default");
            defaultAvatar.setIsCurrent(true);
            defaultAvatar.setUploadTime(LocalDateTime.now());
            defaultAvatar.setCreatedBy("system");
            defaultAvatar.setUpdatedTime(LocalDateTime.now());
            defaultAvatar.setFileSize(0);
            defaultAvatar.setFileFormat("jpg");

            return save(defaultAvatar);

        } catch (Exception e) {
            log.error("设置默认头像失败，患者ID: {}", patientUid, e);
            throw new RuntimeException("设置默认头像失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex > 0 ? filename.substring(lastDotIndex + 1) : "";
    }

    /**
     * 生成唯一文件名
     */
    private String generateUniqueFileName(Long patientUid, String extension) {
        return String.format("avatar_%d_%s.%s", patientUid, UUID.randomUUID().toString().replace("-", ""), extension);
    }

    /**
     * 从URL中提取对象名称
     */
    private String extractObjectNameFromUrl(String url) {
        if (StrUtil.isBlank(url)) {
            return null;
        }
        // 根据实际的OSS URL格式提取对象名称
        // 这里需要根据你的OSS配置来调整
        try {
            int index = url.indexOf("/patient-avatars/");
            if (index >= 0) {
                return url.substring(index + 1);
            }
        } catch (Exception e) {
            log.warn("提取对象名称失败: {}", url, e);
        }
        return null;
    }
}